//
//  QRPayVC.swift
//  RPay
//
//  Created by Charlie Liao on 2017/7/5.
//  Copyright © 2017年 Charlie. All rights reserved.
//

class QRPayVC: Pay_ReceiptVC, CTAPIManagerParamSource, CTAPIManagerCallBackDelegate
{
    
    // MARK: - Life Cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = LocalStr("付款")
        discriptionLabel.text = LocalStr("扫一扫上面的二维码，向我收款")
        setBtn.setTitle(LocalStr("转账"), for: .normal)
        // Do any additional setup after loading the view.
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(生成二维码))
        生成二维码()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController!.setNavigationBarHidden(false, animated: animated)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if timer == nil || !timer!.isValid {
            timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(timerCallBack), userInfo: nil, repeats: true)
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if timer != nil && timer!.isValid {
            timer!.invalidate()
        }
    }
    
    // MARK: CTAPIManagerParamSource
    func params(forApi manager: CTAPIBaseManager!) -> [AnyHashable : Any]!
    {
        return [kApiParamGenerateTime: timestamp]
    }
    
    // MARK: CTAPIManagerCallBackDelegate
    func managerCallAPIDidSuccess(_ manager: CTAPIBaseManager!) {
        let amount = manager.fetchData(with: TransferResultReformer())
        
        let vc = PaySucceedVC()
        vc.price = amount as! String
        self.navigationController!.pushViewController(vc, animated: true)
        
        生成二维码()
    }
    
    func managerCallAPIDidFailed(_ manager: CTAPIBaseManager!)
    {
        // 时间差异太大，重新生成二维码
        let dt = difftime - InterfaceShare.shared.difftime
        if dt >= 10000 || dt <= -10000 { // 毫秒级，差异大于10秒
            生成二维码()
        }
    }
    
    // MARK: - Event respond
    /// 点击设置金额按钮
    override func tapSetAmountBtn() {
        let vc = TransferVC()
        navigationController!.pushViewController(vc, animated: true)
    }
    
    // MARK: - Private
    func 生成二维码() {
        difftime = InterfaceShare.shared.difftime
        
        let userName = UserShare.shared.loginUser!.userName
        timestamp = NSDate(timeIntervalSinceNow: TimeInterval(difftime/1000)).timestamp
        let type = kApiParamTransferTypePay
        
        let codestr = "\(userName)|0|\(timestamp!)|\(type)"
        //        let codestr = "twuser|0|1501658622000|\(type)"
        //        let codestr = "cnuser|0.00|1498303791079|01"
        
        let data = codestr.data(using: .utf8)! as NSData
        let cData = data.encryptDES(withKey: "Rpay2017")
        let rqCodeStr = cData!.base64EncodedString()
        QRcodeImgView.image = rqCodeStr.generateQRCodeWithLogo(logo: #imageLiteral(resourceName: "icon_denglu_logo"))
    }
    
    func timerCallBack() {
        if !apiManager.isLoading {
            apiManager.loadData()
        }
    }
    
    // MARK: -
    var timer: Timer?
    var timestamp: String!
    var difftime: Int64 = 0
    
    lazy var apiManager : TransferResultApiManager = {
        let _apiManager = TransferResultApiManager()
        _apiManager.delegate = self
        _apiManager.paramSource = self
        return _apiManager
    }()
}
